﻿using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;

namespace huqiang.Communication
{
    public static class DataExtand
    {
        static byte[] Zreo = new byte[4];
        public unsafe static byte[] GetByteArray(byte* p, int len)
        {
            byte[] buff = new byte[len];
            for (int i = 0; i < len; i++)
            { buff[i] = *p; p++; }
            return buff;
        }
        public unsafe static byte[] ToBytes(this Int16 value)
        {
            byte[] buff = new byte[2];
            fixed (byte* bp = &buff[0])
                *(Int16*)bp = value;
            return buff;
        }
        public unsafe static byte[] ToBytes(this Int32 value)
        {
            byte[] buff = new byte[4];
            fixed (byte* bp = &buff[0])
                *(Int32*)bp = value;
            return buff;
        }
        public unsafe static byte[] ToBytes(this Single value)
        {
            byte[] buff = new byte[4];
            fixed (byte* bp = &buff[0])
                *(Single*)bp = value;
            return buff;
        }
        public unsafe static byte[] ToBytes(this Int64 value)
        {
            byte[] buff = new byte[8];
            fixed (byte* bp = &buff[0])
                *(Int64*)bp = value;
            return buff;
        }
        public unsafe static byte[] ToBytes(this Double value)
        {
            byte[] buff = new byte[8];
            fixed (byte* bp = &buff[0])
                *(Double*)bp = value;
            return buff;
        }
        public unsafe static Int32 ReadInt32(this byte[] buff, Int32 offset)
        {
            fixed (byte* bp = &buff[0])
                return *(Int32*)(bp + offset);
        }
        public unsafe static Int64 ReadInt64(this byte[] buf, Int32 index)
        {
            unsafe
            {
                fixed (byte* bp = &buf[index])
                    return *(Int64*)bp;
            }
        }
        public unsafe static void Read(this byte[] buff, void* p, int offset, int size)
        {
            byte* bp = (byte*)p;
            for (int i = 0; i < size; i++)
            {
                *bp = buff[offset];
                bp++;
                offset++;
            }
        }
    }
}
